//
//  WorkorderViewController.m
//  CarLife
//
//  Created by yu on 2018/1/26.
//  Copyright © 2018年 jpas. All rights reserved.
//

#import "WorkorderViewController.h"

#import "VisitingFamilyViewController.h"
#import "WorkorderCell.h"
#import "WorkorderModel.h"
#import "NewInstallViewController.h"

@interface WorkorderViewController ()<UITableViewDelegate,UITableViewDataSource,DZNEmptyDataSetSource,
DZNEmptyDataSetDelegate>

@property (weak, nonatomic) IBOutlet UIView *containerView;
@property (strong, nonatomic) IBOutlet UIView *btnsView;
@property (weak, nonatomic) IBOutlet UIView *bottomView;
@property (strong, nonatomic) IBOutletCollection(UIButton) NSArray *btns;
@property (nonatomic, strong) UIButton *tempBtn;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, copy) NSString *status;
@property (nonatomic, strong) NSMutableArray *workorderList;
@property (nonatomic, assign) NSInteger page;
@property (nonatomic, assign) NSInteger selectIndex;

@end

static NSString *kWorkorderCellIdentifier = @"WorkorderCell";

@implementation WorkorderViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.fd_interactivePopDisabled = YES;
    self.view.backgroundColor = kBackGroundLightGrayColor;
    self.navigationItem.title = @"工单";
    self.page = 1;
    [self.tableView registerNib:NIB_NAMED(@"WorkorderCell") forCellReuseIdentifier:kWorkorderCellIdentifier];
    self.tableView.tableFooterView = [UIView new];
    self.status = @"9";
    
    [self loadWorkorderList];
//    CLUser *user = [CLUser sharedUser];
//    PPLog(@"workorderUploadInstallerLocation22 = %@",user.latitude);
    if ([User sharedUser].latitude.length) {
        [self uploadInstallerLocation];
    }
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadWorkorderList)];
    
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreWorkorderList)];
    // 设置底部inset
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 25, 0);
    // 忽略掉底部inset
    self.tableView.mj_footer.ignoredScrollViewContentInsetBottom = 25;
    // 提交成功
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadWorkorderList) name:@"kReloadWorkOrderListNotification" object:nil];
}

- (void)uploadInstallerLocation
{
    User *user = [User sharedUser];
    [self.requestTool uploadInstallerLocationByInstallId:self.installId lat:user.latitude lng:user.longitude success:^{
        PPLog(@"upload installer location success");
    } failure:^(NSString *error) {
        PPLog(@"upload installer location error = %@",error);
    }];
}

- (void)setTableView:(UITableView *)tableView
{
    _tableView = tableView;
    if (@available(iOS 13.0, *)) {
        UIColor *bgColor = [UIColor colorWithDynamicProvider:^UIColor * _Nonnull(UITraitCollection * _Nonnull traitCollection) {
            if (traitCollection.userInterfaceStyle == UIUserInterfaceStyleLight) {
                return kBackGroundLightGrayColor;
            } else {
                return UIColor.systemBackgroundColor;
            }
        }];
        _tableView.backgroundColor = bgColor;
    } else {
        _tableView.backgroundColor = kBackGroundLightGrayColor;
    }
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"kReloadWorkOrderListNotification" object:nil];
}

#pragma mark -load new data -
- (void)loadWorkorderList
{
    self.page = 1;
    [self.requestTool workorderFind:self.installId page:self.page status:self.status str:@"" success:^(NSMutableArray *workorderList) {
        [self.tableView.mj_header endRefreshing];
        if (workorderList) {
            self.workorderList = workorderList;
            PPLog(@"工单个数:%ld",self.workorderList.count);
            [self.tableView reloadData];
        }
    } failure:^(NSString *error) {
        [self.tableView.mj_header endRefreshing];
    }];
}

#pragma mark -load more data-
- (void)loadMoreWorkorderList
{
    self.page++;
    [self.requestTool workorderFind:self.installId page:self.page status:self.status str:@"" success:^(NSMutableArray *workorderList) {
        [self.tableView.mj_footer endRefreshing];
        if (workorderList) {
            [self.workorderList addObjectsFromArray:workorderList];
            PPLog(@"工单个数:%ld",self.workorderList.count);
            [self.tableView reloadData];
        }
    } failure:^(NSString *error) {
        [self.tableView.mj_footer endRefreshing];
    }];
}

- (void)setContainerView:(UIView *)containerView {
    _containerView = containerView;
    [containerView addSubview:_btnsView];
    _btnsView.sd_layout.spaceToSuperView(UIEdgeInsetsZero);
}

- (void)setBtns:(NSArray *)btns
{
    _btns = btns;
    for (UIButton *btn in btns) {
        if (@available(iOS 13.0, *)) {
            [btn setTitleColor:UIColor.labelColor forState:UIControlStateNormal];
        } else {
            [btn setTitleColor:kTextBlackColor forState:UIControlStateNormal];
        }
        [btn setTitleColor:kBaseColor forState:UIControlStateSelected];
        if (btn.tag == 1) {
            btn.selected = YES;
            self.tempBtn = btn;
        }
    }
}

- (IBAction)btnsAction:(UIButton *)btn
{
    if (btn != self.tempBtn) {
        self.tempBtn.selected = NO;
        btn.selected = YES;
        self.tempBtn = btn;
    } else {
        self.tempBtn.selected = YES;
    }
    
    [UIView animateWithDuration:0.25f animations:^{
        _bottomView.centerX_sd = (kScreenWidth/6)*(2*btn.tag-1);
    }];
    
    switch (btn.tag)
    {
        case 1:self.status = @"9";break;//已接工单，4->9
        case 2:self.status = @"2";break;//未接工单
        case 3:self.status = @"3";break;//已完成工单
        default:break;
    }
    [self loadWorkorderList];
}

#pragma mark -UITableView
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.workorderList.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return [self.tableView cellHeightForIndexPath:indexPath model:self.workorderList[indexPath.section] keyPath:@"workorderModel" cellClass:[WorkorderCell class] contentViewWidth:kScreenWidth];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    WorkorderCell *cell = [tableView dequeueReusableCellWithIdentifier:kWorkorderCellIdentifier];
    cell.receiveBtn.tag = indexPath.section+1;
    cell.enterBtn.tag = indexPath.section+1;
    WorkorderModel *workorderModel = self.workorderList[indexPath.section];
    cell.workorderModel = workorderModel;
    
#pragma mark - block
    @weakify(self);
    // 接受工单
    [cell setReceiveWorkorderBlock:^(NSInteger index) {
        WorkorderModel *woModel = self.workorderList[index];
        PPLog(@"receive woId == %@",woModel.woId);
        [self updateWorkorderStatus:woModel IndexPath:indexPath];
    }];
    
    // 进入家访/拍照
    [cell setEnterWorkorderBlock:^(NSInteger index) {
        @strongify(self);
        self.selectIndex = index;
        WorkorderModel *woModel = self.workorderList[index];
        PPLog(@"enter woId == %@",woModel.woId);
        NSString *woOrderType = NSStringFormat(@"%@",woModel.wordOrderType);
        if ([woOrderType isEqualToString:@"4"]) {//家访
            VisitingFamilyViewController *vf = [[VisitingFamilyViewController alloc] init];
            vf.woModel = woModel;
            vf.enterVisType = EnterByTakingPictures;
            [self.navigationController pushViewController:vf animated:YES];
        } else {//新装、拆除...
            NewInstallViewController *ni = [[NewInstallViewController alloc] init];
            ni.woModel = woModel;
            ni.enterInstallType = EnterByNewInstallNormal;
            [self.navigationController pushViewController:ni animated:YES];
        }
    }];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 8;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.0001;
}

- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section {
    UITableViewHeaderFooterView *header = (UITableViewHeaderFooterView *)view;
    header.contentView.backgroundColor = [UIColor clearColor];
}

#pragma mark - receive workorder
- (void)updateWorkorderStatus:(WorkorderModel *)woModel IndexPath:(NSIndexPath *)indexPath
{
    [self.requestTool workorderUpdateStatus:woModel.woId status:@"9" workEqnos:@"1" success:^(BOOL isFinish) {
        if (isFinish) {
            [MBProgressHUD showToast:@"接单成功"];
            [self.workorderList removeObjectAtIndex:indexPath.section];
            [self.tableView deleteSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationNone];
            [self.tableView reloadData];
        }
    } failure:^(NSString *error) {
        PPLog(@"update workorder status error = %@",error);
    }];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    WorkorderModel *woModel = self.workorderList[indexPath.section];
    PPLog(@"woOrderType == %@",woModel.wordOrderType);
    NSString *workOrderType = NSStringFormat(@"%@",woModel.wordOrderType);
    if ([workOrderType isEqualToString:@"4"]) {//家访单
        WorkorderModel *woModel = self.workorderList[indexPath.section];
        VisitingFamilyViewController *vf = [[VisitingFamilyViewController alloc] init];
        vf.woModel = woModel;
        vf.enterVisType = EnterByWorkorderDetail;
        [self.navigationController pushViewController:vf animated:YES];
    } else {//非家访单
        NewInstallViewController *ni = [[NewInstallViewController alloc] init];
        ni.woModel = woModel;
        ni.enterInstallType = EnterByNewInstallDetail;
        [self.navigationController pushViewController:ni animated:YES];
    }
}


- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    return IMAGE_NAMED(@"nodata");
}

-(BOOL)emptyDataSetShouldAllowScroll:(UIScrollView*)scrollView {
    return YES;
}

- (NSMutableArray *)workorderList
{
    if (_workorderList == nil) {
        _workorderList = [NSMutableArray array];
    }
    return _workorderList;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
